#!/bin/bash

# GitBook 部署脚本
# 用法: ./deploy.sh [提交信息]

set -e  # 遇到错误时退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的信息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否有未提交的更改
if ! git diff-index --quiet HEAD --; then
    print_info "检测到文件更改，准备提交..."
else
    print_warning "没有检测到文件更改，是否继续推送？(y/N)"
    read -r response
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        print_info "操作已取消"
        exit 0
    fi
fi

# 添加所有更改
print_info "添加所有更改到暂存区..."
git add -A

# 获取提交信息
if [ $# -eq 1 ]; then
    msg="$1"
else
    # 交互式输入提交信息
    echo
    print_info "请输入本次提交的主要修改内容:"
    echo "提示: 描述你做了什么改动，例如:"
    echo "  - 更新第X章内容"
    echo "  - 修复链接错误"
    echo "  - 添加新的代码示例"
    echo "  - 优化文档结构"
    echo
    read -r -p "提交信息: " msg
    
    # 如果用户没有输入，使用默认信息
    if [ -z "$msg" ]; then
        msg="更新文档内容 $(date '+%Y-%m-%d %H:%M')"
        print_warning "使用默认提交信息: $msg"
    fi
fi

# 提交更改
print_info "提交更改: $msg"
if git commit -m "$msg"; then
    print_success "提交成功"
else
    print_error "提交失败"
    exit 1
fi

# 推送到各个远程仓库
remotes=("origin master" "gitcode" "github" "gitee")
failed_pushes=()

print_info "开始推送到远程仓库..."
echo

for remote in "${remotes[@]}"; do
    if [[ "$remote" == "origin master" ]]; then
        remote_name="origin"
        branch="master"
        print_info "推送到 $remote_name ($branch 分支)..."
        if git push "$remote_name" "$branch"; then
            print_success "✓ 推送到 $remote_name 成功"
        else
            print_error "✗ 推送到 $remote_name 失败"
            failed_pushes+=("$remote_name")
        fi
    else
        print_info "推送到 $remote..."
        if git push "$remote"; then
            print_success "✓ 推送到 $remote 成功"
        else
            print_error "✗ 推送到 $remote 失败"
            failed_pushes+=("$remote")
        fi
    fi
    echo
done

# 总结推送结果
echo "==========================================="
if [ ${#failed_pushes[@]} -eq 0 ]; then
    print_success "所有远程仓库推送成功！"
else
    print_warning "部分远程仓库推送失败:"
    for failed in "${failed_pushes[@]}"; do
        echo "  - $failed"
    done
    print_info "你可以稍后手动重试失败的推送"
fi
echo "==========================================="

